package com.yulang.security.core.filter;

import com.yulang.security.core.controller.CustomLoginController;
import com.yulang.security.core.controller.MobileLoginController;
import com.yulang.security.core.exception.ValidateCodeException;
import com.yulang.security.core.handler.CustomAuthenticationFailHandler;
import com.yulang.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 校验用户输入的验证码是否正确
 */
@Component
public class MobileValidateFilter extends OncePerRequestFilter {

    private final CustomAuthenticationFailHandler customAuthenticationFailHandler;

    public MobileValidateFilter(SecurityProperties securityProperties,
                                   CustomAuthenticationFailHandler customAuthenticationFailHandler) {
        this.customAuthenticationFailHandler = customAuthenticationFailHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if("/mobile/form".equals(request.getRequestURI())
        && request.getMethod().equalsIgnoreCase("post")){
            try {
                validate(request,response,filterChain);
                return;
            }catch (AuthenticationException e){
                customAuthenticationFailHandler.onAuthenticationFailure(request,response,e);
                return;
            }
        }else{
            filterChain.doFilter(request,response);
            return;
        }

    }

    private void validate(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String session = (String)request.getSession().getAttribute(MobileLoginController.SESSION_KEY);
        String code = request.getParameter("code");
        if(StringUtils.equalsIgnoreCase(session,code)){
            chain.doFilter(request,response);
        }else {
            throw new ValidateCodeException("验证码错误！");
        }
    }

}
